package com.ldzysoft.myweather.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.ldzysoft.myweather.activity.MainActivity;
import com.ldzysoft.myweather.activity.WeatherActivity;
import com.ldzysoft.myweather.db.City;
import com.ldzysoft.myweather.db.County;
import com.ldzysoft.myweather.db.Province;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import com.ldzysoft.myweather.R;
import com.ldzysoft.myweather.utils.HttpUtil;
import com.ldzysoft.myweather.utils.JsonUtil;

public class ChooseAreaFragment extends Fragment {

    private static final String TAG = "ChooseAreaFragment";

    // 省、市、县级别
    private static final int LEVEL_PROVINCE = 0;
    private static final int LEVEL_CITY = 1;
    private static final int LEVEL_COUNTY = 2;
    private int currentLevel;

    // 省、市、县列表
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;

    // 选中的省、市
    private Province selectedProvince;
    private City selectedCity;

    // 控件
    private ProgressDialog progressDialog;
    private TextView title;
    private Button back;

    // 列表控件及其适配器
    private ListView lv;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();

    // 必须提供无参的构造函数，否则会抛异常：Could not find Fragment constructor
    public ChooseAreaFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 填充布局文件，生成碎片视图
        View view = inflater.inflate(R.layout.fragment_area, container, false);

        // 获取碎片上的控件
        title = view.findViewById(R.id.title);
        back = view.findViewById(R.id.back);
        lv = view.findViewById(R.id.lv);

        // 设置适配器
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        lv.setAdapter(adapter);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        queryProvinces();  // 获取全国所有的省份

        // 监听ListView选项的点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (currentLevel) {
                    case LEVEL_PROVINCE:
                        selectedProvince = provinceList.get(position);
                        queryCities();  // 获取省份下的城市
                        break;

                    case LEVEL_CITY:
                        selectedCity = cityList.get(position);
                        queryCounties();  // 获取城市下的县
                        break;

                    case LEVEL_COUNTY:
                        String weatherId = countyList.get(position).getWeatherId();
                        if (getActivity() instanceof MainActivity) {
                            // 当前位于选择城市的碎片页，应跳转到选中城市的天气页
                            Intent intent = new Intent(getActivity(), WeatherActivity.class);
                            intent.putExtra("weather_id", weatherId);
                            startActivity(intent);
                            getActivity().finish();
                        } else if (getActivity() instanceof WeatherActivity) {
                            // 当前位于天气页，应收起ListView控件并请求选中城市的天气信息
                            WeatherActivity activity = (WeatherActivity) getActivity();
                            activity.drawerLayout.closeDrawers();
                            activity.swipeRefresh.setRefreshing(true);
                            activity.requestWeather(weatherId);
                        }
                        break;
                }
            }
        });

        // 监听返回按钮的点击事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (currentLevel) {
                    case LEVEL_COUNTY:
                        queryCities();
                        break;

                    case LEVEL_CITY:
                        queryProvinces();
                        break;
                }
            }
        });
    }

    /*
     * 根据网址和类型，从服务器查询省、市、县的数据
     * */
    private void queryFromServer(String address, String type) {
        showProgressDialog();

        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 数据下载失败，回到主线程
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "onFailure：数据下载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data = response.body().string();
                boolean result = false;

                // 解析服务器返回的数据，并写入数据库
                switch (type) {
                    case "province":
                        result = JsonUtil.handleProvinceData(data);
                        break;

                    case "city":
                        result = JsonUtil.handleCityData(data, selectedProvince.getId());
                        break;

                    case "county":
                        result = JsonUtil.handleCountyData(data, selectedCity.getId());
                        break;
                }

                // 数据处理成功，回到主线程并从数据库中查询
                if (result) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();

                            switch (type) {
                                case "province":
                                    queryProvinces();
                                    break;

                                case "city":
                                    queryCities();
                                    break;

                                case "county":
                                    queryCounties();
                                    break;
                            }
                        }
                    });
                }
            }
        });
    }

    /*
     * 查询全国所有的省份
     * */
    private void queryProvinces() {
        title.setText("中国");
        back.setVisibility(View.GONE);  // 最高级别，无法回退

        provinceList = LitePal.findAll(Province.class);
        if (provinceList.size() > 0) {
            // 数据库能查到
            dataList.clear();
            for (Province province : provinceList) {
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            lv.setSelection(0);  // 选中第0项
            currentLevel = LEVEL_PROVINCE;
        } else {
            // 数据库查不到，从服务器查
            String address = "http://guolin.tech/api/china";
            Log.e(TAG, address);
            queryFromServer(address, "province");
        }
    }

    /*
     * 查询选中省份所有的城市
     * */
    private void queryCities() {
        title.setText(selectedProvince.getProvinceName());
        back.setVisibility(View.VISIBLE);  // 当前为指定省份，可以回退到全国省份列表

        cityList = LitePal.where("provinceId = ?", String.valueOf(selectedProvince.getId()))
                .find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            lv.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            // 接口返回的id实际上是城市的代号，与数据库表中的id不是同一字段
            String address = "http://guolin.tech/api/china/"
                    + String.valueOf(selectedProvince.getProvinceCode());
            Log.e(TAG, address);
            queryFromServer(address, "city");
        }
    }

    /*
     * 查询选中城市所有的县
     * */
    private void queryCounties() {
        title.setText(selectedCity.getCityName());
        back.setVisibility(View.VISIBLE);

        countyList = LitePal.where("cityId = ?", String.valueOf(selectedCity.getId()))
                .find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            lv.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            String address = "http://guolin.tech/api/china/"
                    + String.valueOf(selectedProvince.getProvinceCode()) + "/"
                    + String.valueOf(selectedCity.getCityCode());
            Log.e(TAG, address);
            queryFromServer(address, "county");
        }
    }

    /*
     * 显示数据下载进度条
     * */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /*
     * 关闭进度条对话框
     * */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

}
